package com.sky.controller.user;

import com.sky.constant.RedisKeyConstant;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author : by smomo
 * @date : 2023/7/11 15:40
 * @description :
 */
@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品游览接口")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId)
    {

        //缓存菜品
        //1.拼接redis的key:dish:category
        String dishKey= RedisKeyConstant.DISH_PREFIX+categoryId;

        //2.根据key获取菜品获取value
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(dishKey);
        if(dishVOList!=null)
        {
            //2.1如果value值不为空，则直接返回数据
            return Result.success(dishVOList);
        }

        //3.查询数据库
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        List<DishVO> dishVOS = dishService.listWithFlavor(dish);
        //4.缓存穿透处理
        if(dishVOS==null||dishVOS.isEmpty())
        {
            // 4.1获取对象后，对象为空，缓存空值
            redisTemplate.opsForValue().set(dishKey,null);
        }else {
            //4.2将数据缓存到redis
            redisTemplate.opsForValue().set(dishKey,dishVOS);

        }
        return Result.success(dishVOS);
    }


}
